import React, { useEffect, useState } from "react";
import { Breadcrumb } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { useLocation } from "react-router-dom";
import { RootState } from "@/store";
import authRouteList from "@/utils/authRouteList";
import { setPath } from "@/store/modules/breadcrumbSlice.ts";

// 递归查找路径对应的路由
const findRoute = (path: string, routes: any[]): any[] => {
  for (let route of routes) {
    if (route.path === path) {
      return [route];
    }
    if (route.children) {
      const res = findRoute(path, route.children);
      if (res.length > 0) {
        return [route, ...res];
      }
    }
  }
  return [];
};

const LayoutBreadcrumb: React.FC = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const path = useSelector((state: RootState) => state.breadcrumb.path);
  const [breadcrumbItems, setBreadcrumbItems] = useState<any[]>([]);

  useEffect(() => {
    // 更新路径状态
    dispatch(setPath(location.pathname));
  }, [location.pathname, dispatch]);

  useEffect(() => {
    // 查找当前路径对应的面包屑
    const breadcrumbRoutes = findRoute(path, authRouteList);

    // 默认首页项
    const homeBreadcrumbItem = {
      title: "首页", // 确保此值与你的首页标题匹配
      href: "/home/index",
    };

    // 生成面包屑列表
    const breadcrumbList = breadcrumbRoutes.map((route) => ({
      title: route.meta?.title,
      href: route.path,
    }));

    // 检查是否已经包含首页路径，如果不包含则添加到列表前面
    const items = breadcrumbList.some((item) => item.href === homeBreadcrumbItem.href)
      ? breadcrumbList
      : [homeBreadcrumbItem, ...breadcrumbList];

    setBreadcrumbItems(items);
  }, [path]);

  return <Breadcrumb items={breadcrumbItems}></Breadcrumb>;
};

export default LayoutBreadcrumb;
